<template>
  <div class="app-container">
    <el-form
      :model="menu"
      :rules="rules"
      ref="ruleForm"
      label-width="200px"
      class="demo-ruleForm"
    >
      <el-form-item label="显示名" prop="name">
        <el-input v-model="menu.nam"></el-input>
      </el-form-item>
      <el-form-item class="myuploader" label="Menu图片" prop="menuImg">
        <el-upload
          ref="uploader"
          class="upload-demo"
          :on-change="handleChange"
          :action="uploadUrl"
          :file-list="fileList"
          :data="menu"
          :http-request="uploadSectionFile"
          :multiple="false"
          :auto-upload="false"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="链接URL" prop="url">
        <el-input v-model="menu.url"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="menu.remarks"></el-input>
      </el-form-item>
      <el-form-item label="显示排序" prop="orderNum">
        <el-input-number
          v-model="menu.orderNum"
          :min="1"
          :max="999"
          label="排序号"
        ></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { updateMenuApi } from "@/api/menu";
import { getMenuApi } from "@/api/menu";
export default {
  data() {
    return {
      changeMenuImg: false,
      imgPath: process.env.VUE_APP_BASE_API,
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + "/menu",
      menu: {},
      rules: {
        url: [{ required: false, message: "请输入链接URL", trigger: "blur" }],
        orderNum: [
          { required: true, message: "请输入排序号", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.menu.id = this.$route.params.id;
    this.getMenu(this.menu.id);
  },
  methods: {
    getMenu(id) {
      getMenuApi(id).then((response) => {
        this.menu = response.data;
        this.fileList = [
          { name: this.menu.img.substring(this.menu.img.lastIndexOf("/")+1), url: this.imgPath + this.menu.img, status: "ready" },
        ];
        delete this.menu.createTime;
      });
    },
    uploadSectionFile(params) {
      const file = params.file,
        fileType = file.type,
        isImage = fileType.indexOf("image") != -1,
        isLt2M = file.size / 1024 / 1024 < 2;
      // 这里常规检验，看项目需求而定
      if (!isImage) {
        this.$message.error("只能上传图片格式png、jpg、gif!");
        return;
      }
      if (!isLt2M) {
        this.$message.error("只能上传图片大小小于2M");
        return;
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("file", file);
      //遍历menu转formdata格式键值对
      delete this.menu.img;
      Object.keys(this.menu).forEach((key) => {
        form.append(key, this.menu[key]);
      });
      this.updateMenu(form);
    },
    updateMenu(form) {
      updateMenuApi(form).then((res) => {
        if (res.status == 0) {
          this.$message("提交成功");
        }
        this.$router.push("/content/rightmenu");
      });
    },
    handleChange(file, fileList) {
      console.log(file);
      const isPNG = file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 0.5;
      if (fileList.length > 0) {
        //单个覆盖上传
        this.fileList = [fileList[fileList.length - 1]]; // 这一步，是 展示最后一次选择的csv文件
        if (!isPNG) {
          this.$message.error("上传图片只能是 PNG 格式!");
          this.fileList = [];
          return false;
        } else if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 200kb!");
          this.fileList = [];
          return false;
        }
        this.changeMenuImg = true;
        return true;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.changeMenuImg) {
            this.$refs.uploader.submit();
          } else {
            var formData = new FormData();
            Object.keys(this.menu).forEach((key) => {
              formData.append(key, this.menu[key]);
            });
            this.updateMenu(formData);
          }
        }
      });
    },
  },
};
</script>

<style scoped>
.myuploader >>> .el-list-enter-active,
.myuploader >>> .el-list-leave-active {
  transition: none;
}

.myuploader >>> .el-list-enter,
.myuploader >>> .el-list-leave-active {
  opacity: 0;
}
</style>